package com.ergwang.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ergwang.commonutils.R;
import com.ergwang.eduservice.bean.EduTeacher;
import com.ergwang.eduservice.bean.vo.TeacherQuery;
import com.ergwang.eduservice.service.EduTeacherService;
import com.ergwang.servicebase.exceptionhandler.ErgwangException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author ergwang
 * @since 2020-12-04
 */

// 给swagger接口文档加上中文注释
@Api(value = "讲师管理",tags = {"讲师管理"})

@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class EduTeacherController {
    /*
    * 步骤：
    *   1.把service注入(使用注解@Autowired实现)
    *   2.使用service实现功能
    */

    // 注入service
    //数据的list集合

    /** 注入service，
     *  不使用注解@Autowired，
     *  声明一个新的service获得service
     */
    private final EduTeacherService teacherService;

    public EduTeacherController(EduTeacherService teacherService) {
        this.teacherService = teacherService;
    }


    /** 查询讲师表中的所有数据
     * @return R
     */
    @ApiOperation(value = "所有讲师列表") // 给接口功能加一个中文提示
    @GetMapping("findAll")
    public R findAllTeacher(){

        // 测试异常处理
        try{
            int i=10/0;
        }catch (Exception e){
            // 执行自定义异常
            throw  new ErgwangException(10086,"执行了自定义异常.....");
        }

        // 调用service的方法
        return R.ok().data("items",teacherService.list(null));
    }


    /** 讲师的逻辑删除
     * @param id 讲师id
     * @return 结果
     */
    @ApiOperation(value = "根据id逻辑删除讲师") // 给接口功能加一个中文提示
    @DeleteMapping("deleteTeacher/{id}")
    public R deleteTeacher(
            // 给参数加一个中文提示
            @ApiParam(name = "id", value = "讲师id", required = true)
            @PathVariable String id){

        if (teacherService.removeById(id)){
            return R.ok();
        }else{
            return R.error();
        }

    }

    /**
     * 分页查询讲师
     * @param current 当前页
     * @param limit   每页的个数
     * @return    查询结果
     */
    @ApiOperation(value = "分页查询讲师")
    @GetMapping("pageTeacher/{current}/{limit}")
    public R pageListTeacher(@ApiParam(name = "current",value = "当前页", required = true)
                                 @PathVariable long current,
                             @ApiParam(name = "limit", value = "每页个数", required = true)
                                 @PathVariable long limit){
        // 1.创建一个page对象
        Page<EduTeacher> pageTeacher = new Page<>(current,limit);

        // 2.调用方法实现分页
        //   调用方法的时候，底层封装，会把分页的所有数据封装到pageTeacher对象中
        teacherService.page(pageTeacher,null);

        // 获取pageTeacher中的数据
        //总记录数
        long total = pageTeacher.getTotal();
        //数据的list集合
        List<EduTeacher> records = pageTeacher.getRecords();

        return R.ok().data("total",total).data("rows",records);

        // 或者这样写
//        Map map = new HashMap<String,Object>();
//        map.put("total",total);
//        map.put("rows",records);
//
//        return R.ok().data(map);
    }

    /** 条件查询带分页
     * @param current 当前页
     * @param limit  每页行数
     * @param teacherQuery  请求体
     * @return  返回结果集
     */
    @ApiOperation(value = "条件查询带分页")
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    public R pageTeacherCondition(@ApiParam(name = "current",value = "当前页",required = true)
                                      @PathVariable long current,
                                  @ApiParam(name = "limit",value = "每页个数",required = true)
                                      @PathVariable long limit,
                                  @ApiParam(name = "teacherQuery",value = "请求体")
                                      @RequestBody(required = false)  TeacherQuery teacherQuery){
        // 1.创建page对象
        Page<EduTeacher> pageTeacher = new Page<>(current, limit);


        // 2.构建条件
          // a. new 一个wrapper对象
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
          // b. 构建条件，将前端传入的对象写入wrapper中

        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();

        //判断条件值是否为空，不为空就拼接
        if (StringUtils.isNotEmpty(name)){
            wrapper.like("name", name);
        }
        if (null != level){
            wrapper.eq("level", level);
        }
        if (StringUtils.isNotEmpty(begin)){
            wrapper.ge("gmt_create", begin);
        }
        if (StringUtils.isNotEmpty(end)){
            wrapper.le("gmt_create", end);
        }

        // 排序
        wrapper.orderByDesc("gmt_create");


        // 3.调用方法实现条件查询分页
        teacherService.page(pageTeacher,wrapper);

        //总记录数
        // 4.获取pageTeacher中的数据
        long total = pageTeacher.getTotal();
        //数据的list集合
        List<EduTeacher> records = pageTeacher.getRecords();

        return R.ok().data("total",total).data("rows",records);
    }


    /**
     * 添加讲师的接口
     * @param eduTeacher 请求中的teacher封装体数据
     * @return  成功or失败
     */
    @ApiOperation("添加讲师")
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher){
        boolean save = teacherService.save(eduTeacher);
        if (save){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     * 修改讲师信息
     * 先查询再修改
     */

    @ApiOperation("根据id查询讲师")
    @GetMapping("getTeacher/{id}")
    public R getTeacherById(
            @ApiParam(name = "id",value = "讲师id", required = true)
            @PathVariable String id){
        EduTeacher teacher = teacherService.getById(id);
        return R.ok().data("teacher",teacher);
    }

    @ApiOperation("更新讲师信息")
    @PostMapping("updateTeacher")
    @CrossOrigin
    public R updateTeacher(
            @ApiParam(name = "eduTeacher",value = "讲师对象体", required = true)
            @RequestBody EduTeacher eduTeacher){
        boolean update = teacherService.updateById(eduTeacher);
        if (update){
            return R.ok();
        }else {
            return R.error();
        }
    }
}

